import json
import copy


with open(r"patient", encoding="UTF-8") as f:
    df = json.load(f)


def flatten(path, table):
    def walk_down(path_w, pre_w, data):
        cur = path_w.pop()
        pre_w.append([cur, data.copy()])
        data = data.get(cur)
        if len(path_w) == 0:
            r = data
            for i in pre_w[::-1]:
                i[1].update({i[0]: r})
                r = i[1]
            res.append(r)
            return
        if type(data) == list:
            for i in data:
                pre_ww = copy.deepcopy(pre_w)
                path_ww = copy.deepcopy(path_w)
                walk_down(path_ww, pre_ww, i)
        elif type(data) == dict:
            walk_down(path_w, pre_w, data)
        else:
            print("中间路径存在非list或dict！")

    res = []
    path = path.split(".")[::-1]
    table = table.get(path.pop())
    for struct in table:
        pre = []
        path_struct = copy.deepcopy(path)
        walk_down(path_struct, pre, struct)
    return res


if __name__ == '__main__':)
    flatten_table = flatten('A.B.C', df)
